package grabbing.ticket.common.util.redis;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Optional;
import java.util.concurrent.TimeUnit;

/**
 * 分布式锁
 *
 * @author lcf
 */
@Component
public class RedisLockUtils{

    @Autowired
    protected StringRedisTemplate redisTemplate;

    private static final String LOCK_KEY = "lock";

    /**
     * 是否存在
     */
    public boolean hasKey() {
        return Optional.ofNullable(redisTemplate.hasKey(LOCK_KEY)).orElse(false);
    }

    /**
     * 获取锁
     */
    public boolean lock(long seconds) {
        if (hasKey()) {
            return false;
        }

        redisTemplate.setEnableTransactionSupport(true);
        redisTemplate.watch(LOCK_KEY);
        redisTemplate.multi();

        redisTemplate.boundValueOps(LOCK_KEY).set("");
        redisTemplate.expire(LOCK_KEY, seconds, TimeUnit.SECONDS);

        List<Object> list = redisTemplate.exec();
        redisTemplate.unwatch();

        return CollectionUtils.isNotEmpty(list);
    }

    /**
     * 获取锁
     */
    public boolean getLock(long seconds) {
        return Optional.ofNullable(redisTemplate.opsForValue().setIfAbsent(LOCK_KEY, "", seconds, TimeUnit.SECONDS)).orElse(false);
    }

    /**
     * 释放锁
     */
    public void unLock() {
        redisTemplate.delete(LOCK_KEY);
    }
}
